import { useState, useCallback } from 'react';
import { File, Play, Image, Music, FileText, CheckCircle2, Circle } from 'lucide-react';
import { clsx } from 'clsx';
import { useAppSelector } from '@/store';
import { formatFileSize, formatDuration } from '@/utils/format';
import './styles.less';

interface FileSelectorProps {
  selectedFiles: string[];
  onFileSelect: (fileIds: string[]) => void;
  multiple?: boolean;
  fileTypes?: ('video' | 'audio' | 'image' | 'document')[];
  maxFiles?: number;
  showPreview?: boolean;
  className?: string;
}

const getFileIcon = (_type: string, mimeType: string) => {
  if (mimeType.startsWith('video/')) return Play;
  if (mimeType.startsWith('audio/')) return Music;
  if (mimeType.startsWith('image/')) return Image;
  if (mimeType.includes('text') || mimeType.includes('document')) return FileText;
  return File;
};

const getFileTypeColor = (mimeType: string) => {
  if (mimeType.startsWith('video/')) return 'text-blue-600 bg-blue-50';
  if (mimeType.startsWith('audio/')) return 'text-green-600 bg-green-50';
  if (mimeType.startsWith('image/')) return 'text-purple-600 bg-purple-50';
  return 'text-gray-600 bg-gray-50';
};

export const FileSelector: React.FC<FileSelectorProps> = ({
  selectedFiles,
  onFileSelect,
  multiple = true,
  fileTypes = ['video'],
  maxFiles = 10,
  showPreview = true,
  className,
}) => {
  const { recentFiles } = useAppSelector(state => state.video);
  const [searchTerm, setSearchTerm] = useState('');

  // Filter files based on type and search
  const filteredFiles = recentFiles.filter(file => {
    // Type filter
    if (fileTypes.length > 0) {
      const matchesType = fileTypes.some(type => {
        switch (type) {
          case 'video':
            return (
              file.format.toLowerCase().includes('video') ||
              ['mp4', 'avi', 'mov', 'mkv', 'webm'].includes(file.format.toLowerCase())
            );
          case 'audio':
            return (
              file.format.toLowerCase().includes('audio') ||
              ['mp3', 'wav', 'aac', 'flac'].includes(file.format.toLowerCase())
            );
          case 'image':
            return (
              file.format.toLowerCase().includes('image') ||
              ['jpg', 'jpeg', 'png', 'gif', 'webp'].includes(file.format.toLowerCase())
            );
          case 'document':
            return ['pdf', 'doc', 'docx', 'txt'].includes(file.format.toLowerCase());
          default:
            return true;
        }
      });
      if (!matchesType) return false;
    }

    // Search filter
    if (searchTerm) {
      const term = searchTerm.toLowerCase();
      return (
        file.name.toLowerCase().includes(term) || file.originalName.toLowerCase().includes(term)
      );
    }

    return true;
  });

  const handleFileClick = useCallback(
    (fileId: string) => {
      if (multiple) {
        const newSelection = selectedFiles.includes(fileId)
          ? selectedFiles.filter(id => id !== fileId)
          : selectedFiles.length < maxFiles
            ? [...selectedFiles, fileId]
            : selectedFiles;
        onFileSelect(newSelection);
      } else {
        onFileSelect(selectedFiles.includes(fileId) ? [] : [fileId]);
      }
    },
    [selectedFiles, onFileSelect, multiple, maxFiles]
  );

  const handleSelectAll = () => {
    if (selectedFiles.length === filteredFiles.length) {
      onFileSelect([]);
    } else {
      const fileIds = filteredFiles.slice(0, maxFiles).map(f => f.id);
      onFileSelect(fileIds);
    }
  };

  return (
    <div className={clsx('file-selector', className)}>
      {/* Search and Controls */}
      <div className='file-selector__header'>
        <div className='file-selector__search'>
          <input
            type='text'
            placeholder='搜索文件...'
            value={searchTerm}
            onChange={e => setSearchTerm(e.target.value)}
            className='file-selector__search-input'
          />
        </div>

        {multiple && filteredFiles.length > 0 && (
          <button type='button' onClick={handleSelectAll} className='file-selector__select-all'>
            {selectedFiles.length === filteredFiles.length ? '取消全选' : '全选'}
          </button>
        )}
      </div>

      {/* File List */}
      <div className='file-selector__list'>
        {filteredFiles.length === 0 ? (
          <div className='file-selector__empty'>
            <File className='w-12 h-12 text-gray-400 mx-auto mb-4' />
            <p className='text-gray-500'>{searchTerm ? '未找到匹配的文件' : '暂无可选文件'}</p>
            {searchTerm && (
              <button
                onClick={() => setSearchTerm('')}
                className='text-primary-600 hover:text-primary-700 mt-2'
              >
                清除搜索条件
              </button>
            )}
          </div>
        ) : (
          filteredFiles.map(file => {
            const isSelected = selectedFiles.includes(file.id);
            const FileIcon = getFileIcon(file.format, file.format);
            const colorClasses = getFileTypeColor(file.format);

            return (
              <div
                key={file.id}
                className={clsx(
                  'file-selector__item',
                  isSelected && 'file-selector__item--selected'
                )}
                onClick={() => handleFileClick(file.id)}
              >
                <div className='file-selector__item-selection'>
                  {isSelected ? (
                    <CheckCircle2 className='w-5 h-5 text-primary-600' />
                  ) : (
                    <Circle className='w-5 h-5 text-gray-400' />
                  )}
                </div>

                <div className={clsx('file-selector__item-icon', colorClasses)}>
                  <FileIcon className='w-5 h-5' />
                </div>

                <div className='file-selector__item-info'>
                  <div className='file-selector__item-name'>{file.name}</div>
                  <div className='file-selector__item-meta'>
                    {formatFileSize(file.size)}
                    {file.duration && ` • ${formatDuration(file.duration)}`}
                    {file.resolution && ` • ${file.resolution.width}x${file.resolution.height}`}
                  </div>
                </div>

                {showPreview && file.thumbnail && (
                  <div className='file-selector__item-preview'>
                    <img src={file.thumbnail} alt='' className='file-selector__preview-image' />
                  </div>
                )}
              </div>
            );
          })
        )}
      </div>

      {/* Selection Info */}
      {selectedFiles.length > 0 && (
        <div className='file-selector__info'>
          <p>
            已选择 {selectedFiles.length} 个文件
            {multiple && maxFiles > 1 && ` / 最多 ${maxFiles} 个`}
          </p>
        </div>
      )}
    </div>
  );
};

export default FileSelector;
